package cn.edu.shengda;
//https://www.cnblogs.com/tdcqma/p/4763952.html
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class BroadCast extends JFrame implements ActionListener {
    JTextArea textArea;
    JTextField textField;
    JButton button;

    int port=5858;
    InetAddress group=null;
    MulticastSocket socket=null;

    BroadCast(String title) {
        super(title);
        this.setBounds(0,0,800,600);
        this.setLayout(new FlowLayout());
        textArea=new JTextArea(10,10);
        JLabel label=new JLabel("请输入想发送的话：");
        textField=new JTextField(10);
        button=new JButton("发送");
        button.addActionListener(this);
        this.add(textArea);
        this.add(label);
        this.add(textField);
        this.add(button);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        try {
            group=InetAddress.getByName("239.255.8.0");
            socket=new MulticastSocket(port);
            socket.setTimeToLive(1);
            socket.joinGroup(group);

        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        MulticastRead thread=new MulticastRead();
        thread.start();
    }
    class MulticastRead extends Thread{

        @Override
        public void run() {
            while(true)
            {
                byte[] data=new byte[1024];
                DatagramPacket packet=new DatagramPacket(data,data.length);
                try {
                    socket.receive(packet);
                    String text=new String(packet.getData());
                    textArea.append(text.trim()+"\r \n");
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }
    public static void main(String[] args){
        BroadCast bc=new BroadCast("广播窗口");
        bc.setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        String text=textField.getText();
        textArea.append(text+'\n');
        DatagramPacket packet=null;
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateStr = sd.format(new Date());
        String sendText=new String(text+dateStr);
        byte data[]=sendText.getBytes();
        packet=new DatagramPacket(data,data.length,group,port);
        System.out.println(new String(data));
        try {
            socket.send(packet);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
